﻿///<reference path="/ScriptsG/DynaContentDynamic.js" />
///<reference path="/Scripts/JQuery/jquery-1.8.3-vsdoc.js" />
///<reference path="/Scripts/Views/_Layout.js" />
///<reference path="/Scripts/ClientComponents/tiny_mce/tiny_mce_src.js" />
///<reference path="/Scripts/ClientComponents/KendoUI/kendo.web-vsdoc.js" />
///<reference path="/Scripts/ClientComponents/cssRefresh/cssRefresh.js" />
///<reference path="/Scripts/JSonModels/JSonModelsMenuEdition1.js" />

//#region Local variables
var savedEvt;
var language;
var menuToToggleActivation;
var AddEditModeAdd = true;
var tLanguages;
var MenuItemAction = new Object();
var editMode = false;
var cmEditor;
var cmWhat; //What is edited : ["js","css","html"]
var cmChanged = false; //true if cmSourceObj.html() != cmEditor.getValue();
var cmInitialContent; //Filled with initial code content when codemirror instanciated

//var enRibbonTabs = { "_00Start": 0, "_01Insert": 1, "_02Layout": 2, "_03Code": 3, "_04Image": 4, "_05Table": 5 };
var enRibbonTabs = { "_00Start": 0, "_01Insert": 1, "_02Layout": 2, "_03Code": 3, "_04Image": 4, "_05Table": 5 };

//#endregion


/*#region Main form*/
$.fn.MainAjaxSuccess = function (a, b, c) {
    if (a.scriptToExecute != null) {
        eval(a.scriptToExecute);
    }
}
/*#endregion*/

//#region DocReady
$.fn.DocReady = function () {
    language = $("#hidLanguage").val();
    $.fn.PrepareLayoutMenus();
    //$(".AddMenuItem").on("click", $.fn.MenuItemAddDialog);
    $(".AddMenuItem").on("click", $.fn.MenuItemAddEditDialog);
    //$(".EditMenuItem").on("click", $.fn.MenuItemEdit);
    $(".EditMenuItem").on("click", $.fn.MenuItemAddEditDialog);
    $(".RemoveMenuItem").on("click", $.fn.MenuItemConfirmRemove);
    $(".Reorder").on("click", $.fn.MoveMenu);
    $(".AdminModeMenuToggleActivation").on("click", $.fn.ToggleActivationConfirmation);
    $("select").kendoDropDownList();
    //$(".ddlDefaultController").on("change", $.fn.SetController);
    $(".k-dropdown").css("width", 566);
    tLanguages = Languages.split(",");
    var mceEditorCount = tinymce.editors.length;
    if (mceEditorCount == 0) {
        $.fn.CreateTinyMCEInstance();
    }
}
//#endregion

//#region TinyMCE Tools

var $ifr;
var $ifrHtml;
var $ifrBody;

$.fn.CreateTinyMCEInstance = function () {
    var divContent = $("#divContent");
    var contentWrapper = $(".content-wrapper");
    var editorWidth = (ContentMinWidth < 1 ? divContent.width() - ((divContent.offset().left - contentWrapper.offset().left) * 2) : ContentMinWidth);
    var editorHeight = (ContentMinHeight < 1 ? $(window).height() : ContentMinHeight);
    var editorLang = language.substring(3, 5);
    tinyMCE.init
    (
        {
            // General options
            elements: "divContent",
            mode: "exact",
            language: editorLang,
            theme: "ribbon",
            plugins: "tabfocus,advimagescale,loremipsum,image_tools,embed,tableextras,style,table,inlinepopups,searchreplace,contextmenu,paste,wordcount,advlist,autosave,save,layer,table,noneditable",
            inlinepopups_skin: 'ribbon_popup',
            noneditable_leave_contenteditable: false,
            width: editorWidth,
            height: editorHeight,
            // Theme options WARNING No space in tab caption
            theme_ribbon_tab1: { title: cap_Ribbon_Tab01_Start,
                items:
                [
                    ["innoToggleEdit"],
                    ["innoSave"],
                    ["paste"],
                    ["cut,copy", "|", "pastetext,pasteword"],
                    ["justifyleft,justifycenter,justifyright,justifyfull,mce_sup",
                        "outdent,numlist,forecolor",
                        "|",
                        "bold,italic,underline,strikethrough,mce_sub",
                        "indent,bullist,backcolor"],
                    ["paragraph", "heading1", "heading2", "heading3", "heading4", "heading5", "heading6"],
                    ["styleselect", "|", "fontselect", "|", "fontsizeselect"],
                    ["search", "|", "replace", "|", "removeformat"],
                ]
            },
            theme_ribbon_tab2: { title: cap_Ribbon_Tab02_Insert,
                items:
                [
                    ["insertlayer,moveforward", "|", "absolute,movebackward"],
                    ["tabledraw"],
                    ["image", "bestandsbeheer_file", "bestandsbeheer_video", "bestandsbeheer_mp3"],
                    ["embed"],
                    ["link", "|", "unlink", "|", "anchor"],
                    ["loremipsum", "|", "charmap", "|", "hr"]
                ]
            },
            theme_ribbon_tab3: { title: cap_Ribbon_Tab03_Layout,
                items:
                [
                    ["innoInsertLayout01", "innoInsertLayout02H", "innoInsertLayout02V", "innoInsertLayout031", "innoInsertLayout032", "innoInsertLayout041", "innoInsertLayout042"]
                ]
            },
            theme_ribbon_tab4: { title: cap_Ribbon_Tab04_Code,
                items:
                [
                    ["innoSourceHTML", "innoSourceCSS"]
                ]
            },
            theme_ribbon_tab5: { title: cap_Ribbon_Tab05_Image,
                bind: "img",
                items:
                    [
                        ["image_float_left", "image_float_right", "image_float_none"],
                        ["image_alt"],
                        ["image_width_plus", "|", "image_width_min", "|", "image_width_original"],
                        ["image_edit", "|", "image_remove"]
                    ]
            },
            theme_ribbon_tab6: { title: cap_Ribbon_Tab06_Table,
                bind: "td",
                items:
                    [
                        ["delete_table"], ["delete_col", "|", "delete_row"],
                        ["col_before", "|", "col_after"],
                        ["row_before", "|", "row_after"]
                    ]
            },
            //Absolute path
            remove_script_host: false,
            convert_urls: false,
            // Skin options
            //////////skin: "o2k7",
            //////////skin_variant: "silver",

            // Example content CSS (should be your site CSS)
            content_css: "/Content/EditableContent/Base.css",

            //Drop lists for link/image/media/template dialogs
            //template_external_list_url: "js/template_list.js",
            //external_link_list_url: "js/link_list.js",
            //external_image_list_url: "js/image_list.js",
            //media_external_list_url: "js/media_list.js",

            file_browser_callback: "filebrowser",
            setup: $.fn.RibbonCustomSetup
        }
    );
    //Detect Ribbon tab click
    //Fix, in this case .on doesnt works
    //$(".ribbon_tab_btn li").on("click", $.fn.RibbonTabOnClick);
    $(".ribbon_tab_btn li").live("click", $.fn.RibbonTabOnClick);
    $(".mce_innoSave").addClass("big");
}
// TinyMCE Customization
$.fn.RibbonCustomSetup = function (ed) {
    ed.onInit.add($.fn.InitTinyMCE);
    // Add a custom button
    ed.addButton
    (
        "innoToggleEdit",
        {
            "label": cap_Ribbon_TogglePreview,
            "title": cap_Ribbon_TogglePreview_Title,
            "class": "big innoToggleEdit_Edit",
            "onclick": $.fn.ToggleEditMode
        }
    );
    ed.addButton
    (
        "innoSave",
        {
            "label": cap_Ribbon_Save,
            "title": cap_Ribbon_Save_Title,
            "class": "big innoSave",
            "onclick": $.fn.SaveContentDialog
        }
    );
    ed.addButton
    (
        "innoInsertLayout01",
        {
            "label": cap_Ribbon_Layout01,
            "title": cap_Ribbon_Layout01_Title,
            "class": "big innoInsertLayout Layout01",
            "onclick": $.fn.GetAndInsertLayout,
            "value": "Layout01"
        }
    );
    ed.addButton
    (
        "innoInsertLayout02H",
        {
            "label": cap_Ribbon_Layout02H,
            "title": cap_Ribbon_Layout02H_Title,
            "class": "big innoInsertLayout Layout02H",
            "onclick": $.fn.GetAndInsertLayout
        }
    );
    ed.addButton
    (
        "innoInsertLayout02V",
        {
            "label": cap_Ribbon_Layout02V,
            "title": cap_Ribbon_Layout02V_Title,
            "class": "big innoInsertLayout Layout02V",
            "onclick": $.fn.GetAndInsertLayout
        }
    );
    ed.addButton
    (
        "innoInsertLayout031",
        {
            "label": cap_Ribbon_Layout031,
            "title": cap_Ribbon_Layout031_Title,
            "class": "big innoInsertLayout Layout031",
            "onclick": $.fn.GetAndInsertLayout
        }
    );
    ed.addButton
    (
        "innoInsertLayout032",
        {
            "label": cap_Ribbon_Layout032,
            "title": cap_Ribbon_Layout032_Title,
            "class": "big innoInsertLayout Layout032",
            "onclick": $.fn.GetAndInsertLayout
        }
    );
    ed.addButton
    (
        "innoInsertLayout041",
        {
            "label": cap_Ribbon_Layout041,
            "title": cap_Ribbon_Layout041_Title,
            "class": "big innoInsertLayout Layout041",
            "onclick": $.fn.GetAndInsertLayout
        }
    );
    ed.addButton
    (
        "innoInsertLayout042",
        {
            "label": cap_Ribbon_Layout042,
            "title": cap_Ribbon_Layout042_Title,
            "class": "big innoInsertLayout Layout042",
            "onclick": $.fn.GetAndInsertLayout
        }
    );
    ed.addButton
    (
        "innoSourceHTML",
        {
            "label": cap_Ribbon_SourceHTML,
            "title": cap_Ribbon_SourceHTML_Title,
            "class": "big innoSourceHTML SourceHTML",
            "onclick": $.fn.SourceHTML
        }
    );
    ed.addButton
    (
        "innoSourceCSS",
        {
            "label": cap_Ribbon_SourceCSS,
            "title": cap_Ribbon_SourceCSS_Title,
            "class": "big innoSourceCSS SourceCSS",
            "onclick": $.fn.SourceCSS
        }
    );
}


$.fn.InitTinyMCE = function (ed) {
    var $ed = $("#" + ed.id + "_tbl");
    var $tbr = $ed.find("tr:nth(1)");
    /*globals*/
    $ifr = $("#" + ed.id + "_ifr");
    $ifrHtml = $ifr.find("html");
    $ifrBody = $ifr.find("#tinymce");
    /**/

    $ifr.attr("marginwidth", "0");
    $ifr.attr("marginheight", "0");
    $ifr.css("margin", "0");
    $ifr.css("padding", "0");
    $ifr.css("background", "transparent");

    $ribbonTable = $("#divMceRibbonBarPlaceholder").find(":nth-child(1)").find(":nth-child(1)");
    $ribbonTable.css("width", "100%");
    $ribbonTable.css("margin-left", "0px");
    $ribbonTable.css("margin-right", "0px");

    $ifrHtml.css("height", "90%");
    $ifrBody.removeClass("mceContentBody");
    $ifrBody.addClass("ifrEditorFix");

    //$(".mceIframeContainer").css("border", "none");
    $tbr.hide();
    $rbnPH = $("#divMceRibbonBarPlaceholder").find("table");
    $rbnPH.append($tbr);
    $tbr.show();
    $(".AdminModeMenuButtonRight,.AdminModeMenuButtonLeft").css("display", "none");
    editMode = true;
}

$.fn.ToggleEditMode = function (evt) {
    if (!editMode) {
        if (tinymce.editors.length == 0) {
            $.fn.CreateTinyMCEInstance();
        } else {
            tinymce.editors[0].show();
        }
        $(".AdminModeMenuButtonRight,.AdminModeMenuButtonLeft").css("display", "none");
        $(".innoToggleEdit_Preview").addClass("innoToggleEdit_Edit");
        $(".innoToggleEdit_Preview").removeClass("innoToggleEdit_Preview");
        $("#divBody").addClass("editMode");
        editMode = true;
    } else {
        if (tinymce.editors.length > 0) {
            tinymce.editors[0].hide();
        }
        $(".AdminModeMenuButtonRight,.AdminModeMenuButtonLeft").css("display", "");
        $(".innoToggleEdit_Edit").addClass("innoToggleEdit_Preview");
        $(".innoToggleEdit_Edit").removeClass("innoToggleEdit_Edit");
        editMode = false;
    }
    if (evt != null) {
        $.fn.ensureStopPropagation(evt);
    }
}

$.fn.RibbonTabOnClick = function (evt, a, b, c) {
    switch ($(this).index()) {
        case enRibbonTabs._03Code:
            break;
        default:
            $.fn.CodePanelRemove();
            switch ($(this).index()) {
                case enRibbonTabs._02Layout:
                    /*
                    var html = $("#" + "divContent" + "_ifr").contents().find("html");
                    var head = html.find("head");
                    if (!head.html().indexOf("jquery.layout.js")) {
                        $('<link href="/Content/themes/redmond/jquery-ui-1.8.21.custom.css" rel="stylesheet"/>').appendTo(head);
                        $('<link href="/Content/ClientComponents/jquery.layout/jquery.layout.css" rel="stylesheet" type="text/css" />').appendTo(head);
                        $('<script src="/Scripts/JQuery/jquery-1.8.3.js"></script>').appendTo(head);
                        $('<script src="/Scripts/JQuery/jquery-ui-1.9.2.js"></script>').appendTo(head);
                        $('<script src="/Scripts/ClientComponents/jquery.layout/jquery.layout.js" type="text/javascript"></script>').appendTo(head);
                    }
                    var body = html.find("body");
                    body.layout(
                        {
                            applyDefaultStyles: true
                        }
                    );
                    */
                    break;
                default:
                    break;
            }
            break;
    }
}

/*#region CodeMirror event handling*/
///<summary>
///OnChange event handler
///</summary>
$.fn.CodeMirrorChange = function (cm, changeObj) {
    cmChanged = cmInitialContent != cm.getValue();
    var parentItem;
    switch (cmWhat) {
        case "js":
            //NotImplementedYet
            break;
        case "css":
            parentItem = $("#divContent_innoSourceCSS");
            break;
        case "html":
            parentItem = $("#divContent_innoSourceHTML");
            break;
    }
    var divCodeSave = parentItem.find("#divCodeSaveContainer");
    if (cmChanged) {
        $.fn.SaveCancelPanelBuild(parentItem);
    } else {
        $.fn.SaveCancelPanelRemove();
    }
}

$.fn.SaveCancelPanelBuild = function (parentItem) {
    $("#divCodeSaveContainer").remove();
    parentItem.css("display", "block");
    parentItem.css("position", "relative");
    var buttonsHtml = "<div id='divCodeSaveContainer'><div id='divCodeSave'><div id='CodeEditorSave'></div><div id='CodeEditorCancelSave'></div></div></div>";
    parentItem.append(buttonsHtml);
    $("#CodeEditorSave").bind("click", $.fn.SaveCode);
    $("#CodeEditorCancelSave").bind("click", $.fn.CancelSaveCode);

}

$.fn.SaveCode = function () {
    switch (cmWhat) {
        case "js":
            //NotImplementedYet
            break;
        case "css":
            $.fn.codeMirrorSaveCSS();
            break;
        case "html":
            $.fn.codeMirrorSaveHTML();
            break;
    }
}

$.fn.CancelSaveCode = function () {
    cmChanged = false;
    $.fn.codePanel
}

$.fn.SaveCancelPanelRemove = function () {
    $("#divCodeSaveContainer").remove();
}

/*#endregion*/

/*#region code panel management*/
///<summary>
/// Close verify is code panel is changed
/// If yes : Ask for keep changes
/// If no  : close it
///</summary>
///<returns>true if the code can continue, false if not</returns>
$.fn.CodePanelRemove = function () {
    var toReturn = true;
    var cp = $("#divCodePanel");
    if (cp.length > 0) {
        if (cmChanged) {
            $.fn.jqDialogYesNoFunction(cap_CodeMirrorChanged_Title, cap_CodeMirrorChanged, cap_YesButtonCaption, cap_NoButtonCaption, $.fn.codeMirrorDialogApplyChanges, $.fn.codeMirrorDialogCancelChange, $.fn.codeMirrorDialogOpen, 450, 150);
            toReturn = false;
            return toReturn;
        }
        if (cp.length != 0) {
            $.fn.CodePanelRemoveObjects();
        }
    }
    return toReturn;
}

$.fn.CodePanelRemoveObjects = function () {
    //Remove save and cancel button
    $.fn.SaveCancelPanelRemove();
    //RemoveCodePanel
    var cp = $("#divCodePanel");
    if (cp.length > 0) {
        cp.remove();
    }
}

/*#endregion*/

/*#region HTML Management*/
$.fn.SourceHTML = function () {
    if ($.fn.CodePanelRemove()) {
        $.fn.codeMirrorLoadHTML();
    }
}

$.fn.codeMirrorLoadHTML = function () {
    cmWhat = "html";
    var content = tinyMCE.activeEditor.getContent();
    $.fn.buildCodeMirror("htmlmixed", content);
}

$.fn.codeMirrorSaveHTML = function () {
    var newContent = cmEditor.getValue();
    var content = tinyMCE.activeEditor.setContent(newContent, { format: "raw" });
    cmChanged = false;
}


/*#endregion*/

/*#region CSS Management*/
$.fn.SourceCSS = function () {
    if ($.fn.CodePanelRemove()) {
        $.fn.codeMirrorLoadCSS();
    }
}

$.fn.BuildCSSEditor = function (a) {
    if (a.success) {
        cmWhat = "css";
        cmSourceObj: "ajax:css";
        $.fn.buildCodeMirror("css", a.cssContent);
    }
}

$.fn.codeMirrorLoadCSS = function () {
    $.ajax(
    {
        type: "GET",
        url: "/api/CssEdition/" + language,
        data: null,
        contentType: "application/json",
        async: false,
        success: $.fn.BuildCSSEditor,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAjaxError(cap_DialogErrorTitle, (xhr.responseText));
        }
    });
}

$.fn.codeMirrorSaveCSS = function () {
    SaveCss_JSonModel.cssContent = cmEditor.getValue();
    ajaxData = JSON.stringify(SaveCss_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/api/CssEdition/" + language,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.CSSSaved, //CSSSaved called by the server
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAjaxError(cap_DialogErrorTitle, xhr.responseText);
        }
    });
}

$.fn.CSSSaved = function (a) {
    $.fn.jqDialogAlert('My Pretty CMS', a.message, '', 450, 300);
    var queryString = '?reload=' + new Date().getTime();
    $('link[rel="stylesheet"]').each(function () {
        if (this.href.toLowerCase().indexOf("base") >= 0) {
            this.href = this.href.replace(/\?.*|$/, queryString);
        }
    });
    cmChanged = false;
}
/*#endregion*/

$.fn.codeMirrorDialogOpen = function (evt, ui) {
    $(this).parent().children().children('.ui-dialog-titlebar-close').hide();
}

$.fn.codeMirrorDialogApplyChanges = function () {
    var newContent = cmEditor.getValue();
    switch (cmWhat) {
        case "js":
            $.fn.jqDialogAlert(cap_DialogErrorTitle, cap_NotImplemented, '', 250, 300);
            break;
        case "css":
            $.fn.codeMirrorSaveCSS();
            break;
        case "html":
            $.fn.codeMirrorSaveHTML();
            break;
    }
    if ($(this).dialog != null) {
        $(this).dialog("close");
    }
    $.fn.CodePanelRemoveObjects();
}

$.fn.codeMirrorDialogCancelChange = function (evt, ui) {
    cmChanged = false;
    cmEditor.setValue("");
    var cp = $("#divCodePanel");
    if (cp.length != 0) {
        cp.remove();
    }
    $(this).dialog("close");
    $.fn.CodePanelRemoveObjects();
    $.fn.ensureStopPropagation(evt);
}

$.fn.buildCodeMirror = function (mode, content) {
    var cp = $("body").append("<div id='divCodePanel' class='CodePanel'><div id='resizeN'></div><div id='divCodeMirrorCont'></div></div>");
    cmEditor = CodeMirror($("#divCodeMirrorCont")[0],
        {
            value: content,
            mode: mode,
            lineWrapping: true,
            lineNumbers: true,
            tabMode: "indent"
        }
    );
    var totalLines = cmEditor.lineCount();
    var totalChars = cmEditor.getValue().length;
    cmEditor.autoFormatRange({ line: 0, ch: 0 }, { line: totalLines, ch: totalChars });
    cmInitialContent = content;
    cmEditor.on("change", $.fn.CodeMirrorChange);
    var resizeN = $("#resizeN");
    resizeN.draggable(
    {
        axis: "y",
        stop: $.fn.resizeCodePanel
    }
    );
    cmEditor.setCursor(0, 0);
    $.fn.resizeCodePanel();
}

$.fn.resizeCodePanel = function () {
    var sizer = $("#resizeN");
    var cmCont = $("#divCodeMirrorCont");
    var divCodePanel = $("#divCodePanel");
    var newHeight = $(window).height() - sizer.offset().top;
    divCodePanel.css("height", newHeight);
    sizer.css("top", 0);
    cmCont.height(divCodePanel.height() - sizer.height());
    cmEditor.setSize(cmCont.width() - 22, "100%");
}

$.fn.GetAndInsertLayout = function (a) {
    $.fn.jqDialogAlert("Under construction", "This feature will be available soon...", null, null, null);
    return false;
    var buttonId = $(arguments[0].srcElement).parent().attr("id");
    var command = buttonId.substring(21);
    var content = tinyMCE.activeEditor.getContent();
    ajaxData = JSON.stringify({ LayoutId: command, Content: content });
    $.ajax(
        {
            type: "POST",
            url: "/LayoutManager/GetLayout",
            data: ajaxData,
            contentType: "application/json",
            async: false,
            success: $.fn.InsertLayout,
            error: function (xhr, ajaxOptions, thrownError) {
                $.fn.jqDialogError(cap_DialogErrorTitle, (xhr.responseText));
            }
        });
}

$.fn.InsertLayout = function (r) {
    if (r.success) {
        tinyMCE.activeEditor.setContent(r.htmlContent);
    }
}

function filebrowser(field_name, url, type, win) {

    var fileBrowserURL = "/" + language + "/finder";
    var sessionId = $("#hidSessionId").val();

    tinyMCE.activeEditor.windowManager.open({
        title: "Ajax File Manager",
        url: fileBrowserURL,
        width: 950,
        height: 650,
        inline: "yes",
        maximizable: "no",
        close_previous: "no"
    }, {
        window: win,
        input: field_name,
        sessionid: sessionId,
        resizable: "yes"
    });
}

$.fn.RemoveTinyMCEInstance = function () {
    for (var i = 0; i < tinymce.editors.length; i++) {
        tinyMCE.execCommand('mceRemoveControl', false, tinymce.editors[i].id);
    };
}

$.fn.HideTinyMCEInstance = function (ed, evt) {
    for (var i = 0; i < tinymce.editors.length; i++) {
        tinyMCE.get(tinymce.editors[i].id).hide();
    };
}


$.fn.SaveContentDialog = function () {
    $.fn.jqDialogFunction("#divStructurePage", StructurePageEditorTitle, $.fn.SaveContent, null, null);
}

$.fn.SaveContent = function () {
    $(this).dialog("close");
    var content = tinyMCE.activeEditor.getContent();
    $("#hidNewContent").val(content);
    var v = $("#StructurePage_FK_LayoutMenu_Translation").val();
    var form = $("#frmManagedContent");
    $("#divStructurePage").parent().appendTo(form);
    form.attr("action", "/" + $("#hidControllerName").val() + "/Save/" + v);
    form.submit();
}

//#endregion

/*#region Controller choice*/
$.fn.SetController = function (evt) {
    $.fn.ensureStopPropagation(evt);
    $.fn.SetControllerTextBoxValue($(this));
}

$.fn.SetControllerTextBoxValue = function (ddl) {
    var fieldset = ddl.closest("fieldset");
    var LanguageIndex = fieldset.find("select").attr("LanguageIndex");
    var ControllerTextBoxId = "Menus_" + LanguageIndex + "__Controller";
    var ControllerTextBox = $("#" + ControllerTextBoxId);
    var val = ddl.val();
    ControllerTextBox.val(val);
    //    if (val != "") {
    //        ControllerTextBox.attr("readonly", "readonly");
    //        ControllerTextBox.addClass("readonly");
    //    } else {
    //        ControllerTextBox.removeAttr("readonly");
    //        ControllerTextBox.removeClass("readonly");
    //    }
}
/*#endregion*/

//#region AddEdit Menu

$.fn.MenuItemAddEditDialog = function (evt) {
    savedEvt = evt;
    var el = $(this);
    var layoutMenuTranslationId = -1; //-1 for add mode
    if (el.hasClass("EditMenuItem")) {
        layoutMenuTranslationId = el.attr("data-id");
    }
    LayoutMenuItemFeed_JSonModel.HtmlElementTUpdate = "#divMnuItmEdt";
    LayoutMenuItemFeed_JSonModel.DirectURL = el.attr("data-DirectURL");
    LayoutMenuItemFeed_JSonModel.LayoutMenu_Translation_Id = layoutMenuTranslationId = el.attr("data-id");
    //MVC4 Razor Null<int> rendering
    var parentMenuId = el.attr("data-LayoutMenuTranslationLayoutMenuParent");
    LayoutMenuItemFeed_JSonModel.LayoutMenuTranslationLayoutMenuParent = (parentMenuId == 0 ? null : parentMenuId);

    ajaxData = JSON.stringify(LayoutMenuItemFeed_JSonModel);
    $.ajax(
        {
            type: "POST",
            url: "/DynaStructure/LayoutMenuItemFeed/" + $("#hidLanguage").val(),
            data: ajaxData,
            contentType: "application/json",
            async: false,
            success: $.fn.MenuItemEditDialogFeed,
            error: function (xhr, ajaxOptions, thrownError) {
                $.fn.jqDialogError(cap_DialogErrorTitle, (xhr.responseText));
            }
        });
    $.fn.ensureStopPropagation(evt);
}

$.fn.MenuItemEditDialogFeed = function (r) {
    if (r.success) {
        $(r.elementToUpdate).html(r.htmlContent);
        $.fn.jqDialogFunction("#divMnuItmEdt", cap_EditMenuItem, $.fn.MenuItemAddEdit, null, $.fn.PrepareMnuItmEdt);
    } else {
        eval(r.scriptToExecute);
    }
}
$.fn.PrepareMnuItmEdt = function () {
    var loops = tLanguages.length;
    for (var i = 0; i < loops; i++) {
        if ($("#Translations_" + i + "__SortIndex").val() == "1" && $("#Translations_" + i + "__LayoutMenuTranslationLayoutMenuParent").val() == "") {
            $(".hiddenForIndex").addClass("notDisplayed");
            $(".tblFinalUrl").css("width", "");
        } else {
            $(".hiddenForIndex").removeClass("notDisplayed");
            $(".tblFinalUrl").css("width", "600px");
        }
    }
    if (!($("#SortIndex").val() == "1" && $("#FK_LayoutMenu").val() == "")) {
        $.fn.PrepareFriendURL();
    }
}

$.fn.PrepareFriendURL = function () {
    var languageCount = tLanguages.length;
    for (var i = 0; i < languageCount; i++) {
        $("#Translations_" + i + "__ButtonCaption").friendurl({ id: "Translations_" + i + "__MenuNameURLFormatted", divider: '_', transliterate: false });
        $("#Translations_" + i + "__PageTitle").friendurl({ id: "Translations_" + i + "__PageNameURLFormatted", divider: '_', transliterate: false });
    }
}

$.fn.MenuItemAddEdit = function () {
    var form = $("#frmMnuItmEdt");
    if (form.valid()) {
        //Join friendlyURL
        for (var i = 0; i < tLanguages.length; i++) {
            var directURL = "/" + $("#Translations_" + i + "__Language_Language").val() + "/"
                + ($("#Translations_" + i + "__Ancestors").val() == "" ? "" : $("#Translations_" + i + "__Ancestors").val() + "/")
                + $("#Translations_" + i + "__MenuNameURLFormatted").val() + "/"
                + $("#Translations_" + i + "__PageNameURLFormatted").val() + $("#Translations_" + i + "__AdrBldrSuffix").val();
            $("#Translations_" + i + "__DirectURL").val(directURL);
        }
        //This fix a little bug of the ASP.net MVC4 Ajax.BeginForm
        form.attr("action", "/DynaStructure/LayoutMenuItemAddEdit/" + $("#hidLanguage").val());
        form.submit();
        $(this).dialog("close");
    }
}

$.fn.MenuUpdated = function (a, b, c) {
    if (a.success) {
        $(a.divToUpdate).html(a.html);
        if (a.scriptToExecute != null) {
            eval(a.scriptToExecute);
        }
    } else {
        if (a.scriptToExecute != null) {
            eval(a.scriptToExecute);
        }
    }
    if (savedEvt != null) {
        $.fn.ensureStopPropagation(savedEvt);
    }
}

//#endregion

//#region Remove menu
$.fn.MenuItemConfirmRemove = function (evt) {
    savedEvt = evt;
    RemoveLayoutMenu_JSonModel.DirectURL = $(this).attr("data-DirectURL"),
    RemoveLayoutMenu_JSonModel.LayoutMenu_Translation_Id = $(this).attr("data-id"),
    RemoveLayoutMenu_JSonModel.LayoutMenuTranslationLayoutMenuParent = $(this).attr("data-LayoutMenuTranslationLayoutMenuParent")
    MenuItemAction = RemoveLayoutMenu_JSonModel;
    $.fn.jqDialogConfirm(cap_RemoveMenuItemConfirmTitle, cap_RemoveMenuItemConfirmMessage, cap_RemoveMenuItemConfirmOkButtonTitle, cap_RemoveMenuItemConfirmCancelButtonTitle, $.fn.MenuItemRemove, null, null);
    $.fn.ensureStopPropagation(evt);
}

$.fn.MenuItemRemove = function () {
    $('#dialogMessage').dialog('close');
    ajaxData = JSON.stringify(MenuItemAction);
    $.ajax(
    {
        type: "POST",
        url: "/DynaStructure/LayoutMenuItemRemoveItem/" + $("#hidLanguage").val(),
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.MenuUpdated,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, (xhr.responseText));
        }
    });
}
//#endregion

//#region Move menu
$.fn.MoveMenu = function (evt) {
    savedEvt = evt;
    MoveMenuElement_JSonModel.DirectURL = $(this).attr("data-DirectURL");
    MoveMenuElement_JSonModel.LayoutMenu_Translation_Id = $(this).attr("data-id");
    MoveMenuElement_JSonModel.LayoutMenuTranslationLayoutMenuParent = $(this).attr("data-LayoutMenuTranslationLayoutMenuParent");
    MoveMenuElement_JSonModel.Direction = $(this).attr("data-value");
    ajaxData = JSON.stringify(MoveMenuElement_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/DynaStructure/MoveMenuElement/" + $("#hidLanguage").val(),
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.MenuUpdated,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, (xhr.responseText));
        }
    });
    return false;
}
//#endregion

//#region Menu activation
$.fn.ToggleActivationConfirmation = function (evt) {
    savedEvt = evt;
    ToggleActivation_JSonModel.DirectURL = $(this).attr("data-DirectURL");
    ToggleActivation_JSonModel.LayoutMenu_Translation_Id = $(this).attr("data-id");
    ToggleActivation_JSonModel.LayoutMenuTranslationLayoutMenuParent = $(this).attr("data-LayoutMenuTranslationLayoutMenuParent")
    MenuItemAction = ToggleActivation_JSonModel;
    var newStatus = "";
    if ($(this).hasClass("AdminModeMenuToggleActivationOn")) {
        newStatus = cap_ToggleMenuActivationNewStatus_Disabled;
    } else {
        newStatus = cap_ToggleMenuActivationNewStatus_Enabled;
    }
    $.fn.jqDialogConfirm(cap_ToggleMenuActivationTitle, cap_ToggleMenuActivationMessage + newStatus, cap_ToggleMenuActivationOkButtonTitle, cap_ToggleMenuActivationCancelButtonTitle, $.fn.ToggleMenuActivation, null, null);
    $.fn.ensureStopPropagation(evt);
}

$.fn.ToggleMenuActivation = function () {
    $('#dialogMessage').dialog('close');
    ajaxData = JSON.stringify(MenuItemAction);
    $.ajax(
    {
        type: "POST",
        url: "/DynaStructure/ToggleActivation/" + $("#hidLanguage").val(),
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.MenuUpdated,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, (xhr.responseText));
        }
    });
}

//#endregion
